﻿var LOST_SESSION = "Lost_Session";
var ERROR_PAGE = "Error_Page";

$(document).ready(function () {
    if ($("#groupId").val() != "") {
        $("#cboGroup").val($("#groupId").val());
        $("#cboSubGroup").find("option").removeAttr("disabled").removeClass("disabled");

        if ($("#subGroupId").val() != "") {
            $("#btnAddNew").removeClass("disabled");
            $("#btnAddNew").removeAttr("disabled");
        }
    }

    var subGroupValue = $("#subGroupId").val();
    subGroupValue = subGroupValue == "" ? "0" : subGroupValue;
    $("#cboSubGroup").val(subGroupValue);

    $("#btnDelete").click(handleDelete);

    $("#btnAddGroup").click(handleAddGroup);

    $("#btnAddNew").click(function () {
        var groupId = $("#cboGroup").val();
        var subGroupId = $("#cboSubGroup").val();
        var goBack = "?goBack=" + groupId + ";" + subGroupId;
        $("#masterForm").attr("action", "/Master/New" + goBack);
        $("#masterForm").submit();
    });

    $("#cboGroup").change(function () {
        var groupId = $(this).val();

        if (groupId == 0) {
            groupId = "";
        }

        getProducts(groupId, "", 1);

        if (groupId == "") {
            loadComboSubGroup([]);
        }
        else {
            getSubGroup(groupId);
        }
    });

    $("#cboSubGroup").change(function () {
        var subGroupId = $(this).val();

        if (subGroupId == 0) {
            subGroupId = "";
        }

        getProducts($("#cboGroup").val(), subGroupId, 1);

        if (subGroupId == "") {
            $("#btnAddNew").attr("disabled", "disabled");
            $("#btnAddNew").addClass("disabled");
        }
        else {
            $("#btnAddNew").removeAttr("disabled", "disabled");
            $("#btnAddNew").removeClass("disabled");
        }
    });

    $(".link").click(handleClickUpdate);
    $(".checkbox").change(handleSelectChkDel);
    $(".image").click(handleLoadImage);

    registerPaginateClick();
});


var handleAddGroup = function (e) {
    var groupId = $("#cboGroup").val();
    var subGroupId = $("#cboSubGroup").val();
    var goBack = "goBack=" + groupId + ";" + subGroupId;
    redirectToPage("Master", "NewGroup", goBack);
};

function getSelectedId() {
    var idArr = [];

    $(".checkbox:checked").each(function () {
        var chkId = $(this).attr("id");
        idArr.push(chkId.replace("chkDelProduct", ""));
    });

    return idArr;
}

var handleDelete = function (e) {
    if (!confirm("Bạn chắc chắn muốn xóa [những] sản phẩm này?")) {
        return false;
    }

    var data = {
        lstId: JSON.stringify(getSelectedId())
    };

    $.ajax({
        type: "POST",
        url: "/Master/Delete",
        async: false,
        data: data,
        dataType: "json",
        success: function (data) {
            // console.log(data);
            if (data == null || data == ERROR_PAGE) {
                alert("Xóa sản phẩm đã xảy ra lỗi, hãy thử lại.");
            }
            else if (data == LOST_SESSION) {
                redirectToLogin();
            }
            else if (data == PAGE_OK) {
                $(".checkbox:checked").each(function () {
                    $(this).parent().parent().remove();
                });

                handleSelectChkDel();

                alert("Đã xóa [những] sản phẩm thành công");
            }
        }
    });
};

/*
var handleDelete = function (e) {
    if (!confirm("Bạn chắc chắn muốn xóa [những] sản phẩm này?")) {
        return false;
    }


    
    var data = {
        groupId: groupId,
        subGroupId: subGroupId,
        productId: productId
    };

    $.ajax({
        type: "POST",
        url: "/Master/Delete",
        async: false,
        data: data,
        dataType: "json",
        success: function (data) {
            // console.log(data);
            if (data == null || data == ERROR_PAGE) {
                alert("Xóa sản phẩm đã xảy ra lỗi, hãy thử lại.");
            }
            else if (data == LOST_SESSION) {
                redirectToLogin();
            }
            else if (data == PAGE_OK) {
                $("#btnBack").click();
            }
        }
    });
};
*/

var handleSelectChkDel = function (e) {
    if ($(".checkbox:checked").length > 0) {
        $("#btnDelete").removeAttr("disabled");
        $("#btnDelete").removeClass("disabled");
    }
    else {
        $("#btnDelete").attr("disabled", "disabled");
        $("#btnDelete").addClass("disabled");
    }
};

var handleClickUpdate = function () {
    var groupId = $("#cboGroup").val();
    var subGroupId = $("#cboSubGroup").val();
    var goBack = "&goBack=" + groupId + ";" + subGroupId;
    var href = $(this).attr("href") + goBack;
    $(this).attr("href", href);
}

function getProducts(groupId, subGroupId, pageIndex) {
    $.ajax({
        type: "POST",
        url: "/Master/GetListProducts",
        async: false,
        data: {
            groupId: groupId,
            subGroupId: subGroupId,
            pageIndex: pageIndex
        },
        dataType: "json",
        success: function (response) {
            if (response == null || response == ERROR_PAGE) {
                alert("Something wrong was happened");
            }
            else if (response == LOST_SESSION) {
                redirectToLogin();
            }
            else {
                loadProductList(response);
                handleSelectChkDel();
            }
        }
    });
}

function handlePaginate() {
    paginate("pagination", parseInt($("#totalPage").val()), parseInt($("#pageIndex").val()));
    registerPaginateClick();
}

function registerPaginateClick() {
    $("p.pagination a").click(function () {
        if ($(this).hasClass("disabled") || $(this).hasClass("selected")) {
            return false;
        }

        var pageIndex = $("#pageIndex").val();
        var groupId = $("#cboGroup").val();
        var subGroupId = $("#cboSubGroup").val();

        if (groupId == 0) {
            groupId = "";
        }

        if (subGroupId == 0) {
            subGroupId = "";
        }

        getProducts(groupId, subGroupId, pageIndex);
        $(window).scrollTop($(document).height());
    });
}

function loadProductList(data) {
    var bodyTable = $("div.info table tbody").empty();

    if (data == null || data == "") {
        return false;
    }

    // console.log(data);

    var length = data.ProductProfile.length;
    var div = '<tr>' +
                 '<td class="width-20"><input type="checkbox" name="chkDelProducts" id="chkDelProduct" class="checkbox" /></td>' +
                 '<td class="width-100"><a href="#"><img src="@item.ImageName" class="image" alt="" /></a></td>' +
                 '<td class="width-150"><a href="#" class="link" /></td>' +
                 '<td class="width-150"></td>' +
                 '<td class="width-200"></td>' +
                 '<td class="width-55"><a>Sửa</a></td>' +
                 '<td class="width-55"><a>Xóa</a></td>' +
            '</tr>';

    var updateLink = "/Master/Update?";

    for (var i = 0; i < length; i++) {
        var product = data.ProductProfile[i];
        var clone = $(div).clone();
        var tdList = $(clone).find("td");
        var link = updateLink + "groupId=" + product.GroupId + "&subGroupId=" +
                product.SubGroupId + "&productId=" + product.id;
        $(tdList).eq(0).find("input").attr("id", "chkDelProduct" + product.id).change(handleSelectChkDel);
        $(tdList).eq(1).find("img").attr({
            src: product.ImageName,
            productId: product.id,
            groupId: product.GroupId,
            subGroupId: product.SubGroupId
        }).click(handleLoadImage);
        $(tdList).eq(2).find("a").attr("href", link).text(product.Name).click(handleClickUpdate);
        $(tdList).eq(3).text(product.Price + " VNĐ");
        $(tdList).eq(4).text(product.Description);
        $(bodyTable).append(clone);
    }

    $("#totalPage").val(data.PageCount);
    $("#pageIndex").val(data.CurrentPage);
    handlePaginate();
}

function getSubGroup(id) {
    $.ajax({
        type: "POST",
        url: "/Master/GetSubGroup",
        async: false,
        data: {
            itemGroupId: id
        },
        dataType: "json",
        success: function (response) {
            if (response == null || response == ERROR_PAGE) {
                alert("Something wrong was happened");
            }
            else if (response == LOST_SESSION) {
                redirectToLogin();
            }
            else {
                loadComboSubGroup(response);
            }
        }
    });
}

function loadComboSubGroup(data) {
    // console.log(data);
    $("#cboSubGroup").empty();

    data.insert(0, { id: 0, SubGroupName: "Chọn nhóm con" });

    var length = data.length;

    for (var i = 0; i < length; i++) {
        var option = $("<option value=''></option>");
        $(option).attr("value", data[i].id);
        $(option).text(data[i].SubGroupName);
        $("#cboSubGroup").append(option);
    }

    if (length == 1) {
        $("#cboSubGroup").attr("disabled", "disabled");
        $("#cboSubGroup").addClass("disabled");
    }
    else {
        $("#cboSubGroup").removeAttr("disabled", "disabled");
        $("#cboSubGroup").removeClass("disabled");
    }
}

var handleLoadImage = function (e) {
    var action = "/Master/LoadAllThumnail";
    var groupId = $(this).attr("groupId");
    var subGroupId = $(this).attr("subGroupId");
    var productId = $(this).attr("productId");
    var param = "?groupId=" + groupId + "&subGroupId=" + subGroupId +
        "&productId=" + productId;
    $("#toPopup").removeClass("mediumSize").addClass("largeSize");
    $("#popup").removeClass("mediumSize").addClass("largeSize");
    $("#popup").attr("src", action + param);
    showPopup();
    return false;
}